<template>
	<view class="page-container">
		<!-- 信息录入区 -->
		<view class="info-section">
			<u-cell-group>
				<!-- 循环渲染基础信息 -->
				<u-cell :title="item.label" :value="info[item.prop]" v-for="(item, index) in formList" :key="item.prop"
					:required="item.required">
					<template slot="value">
						<view v-if="item.type!=='dict'" style="word-break: break-all;">
							{{info[item.prop]}}
						</view>
						<view v-else>
							<dicts-tag :list="dictList[item.dictType]" :value="info[item.prop]"></dicts-tag>
						</view>
					</template>
				</u-cell>
				<!-- 解决方案上传 -->
				<u-cell title="解决方案">
					<file-upload slot="value" :list="fileList" disable accept="file" style="margin-top: 12px;"
						@updataFile="updataImage"></file-upload>
				</u-cell>
			</u-cell-group>
		</view>


		<type-title text="消缺问题"></type-title>
		<!-- problemStatus 1 待完成 2 已完成 3 未完成 -->
		<view v-for="(item,index) in info.problemList">
			<view class="question-title-item">
				问题{{index + 1}}
			</view>
			<view class="question-box">
				<view class="question-box-left">
					<view class="question-box-item">
						<text>问题描述：</text>
						<text>{{item.problemDesc}}</text>
					</view>
					<view class="question-box-item">
						<text>问题描述：</text>
						<text>{{item.problemAddress}}</text>
					</view>
					<view class="question-box-item">
						<text>是否完成：</text>
						<text v-if="type == '2' ">
							<text class="color-blue" v-if="item.problemStatus === '1'">待完成</text>
							<text class="color-green" v-if="item.problemStatus === '2'">是</text>
							<text class="color-red" v-if="item.problemStatus === '3'">否</text>
						</text>
						<text v-else>
							<u-radio-group v-model="item.problemStatus" placement="row">
								<u-radio :customStyle="{marginRight: '8px'}" v-for="(item, index) in radiolist"
									:key="index" :label="item.name" :name="item.value">
								</u-radio>
							</u-radio-group>
						</text>
					</view>
					<view class="question-box-item" v-if="item.problemStatus === '3'">
						<text>问题原因：</text>
						<text v-if="info.problemStatus !='3' && type == '2' ">
							{{item['problemCause']}}
						</text>
						<text v-else>
							<u--textarea autoHeight v-model="item['problemCause']" placeholder="请输入内容"></u--textarea>
						</text>
					</view>

					<view class="question-box-item">
						<text>解决时间：</text>
						<text>
							<uni-datetime-picker type="datetime" :clear-icon="true" v-model="item.problemSolveDate" />
						</text>
					</view>
					<view class="question-box-item">
						<text>处理过程：</text>
						<text>
							<u--textarea style="margin-top: 12px;" v-model="item.process" autoHeight
								placeholder="请输入处理过程"></u--textarea>
						</text>
					</view>
					<view class="question-box-item">
						<text>处理结果：</text>
						<text>
							<u--textarea style="margin-top: 12px;" v-model="item.result" autoHeight
								placeholder="请输入处理过程"></u--textarea>
						</text>
					</view>


					<view class="question-box-btn">
						<u-button color="#42b983" @click="handleItemComplete(item,index + 1)"
							style="width: 120px;margin-right: 0;" type="success" text="确认完成"></u-button>
					</view>
				</view>
			</view>

		</view>


		<view class="result-box" v-if="info.problemStatus !='3' && type == '2' ">
			<type-title text="处理结果"></type-title>
			<u-cell-group>
				<!-- 循环渲染基础信息 -->
				<u-cell title="处理过程" :value="info.process">
				</u-cell>
				<u-cell title="处理结果" :value="info.result">
				</u-cell>
				<u-cell title="解决时间" :value="info.taskSolveDate">
				</u-cell>
				<u-cell title="结果附件">
					<template slot="value">
						<file-upload style="margin-top: 12px;" :list="imageList" disable></file-upload>
					</template>
				</u-cell>
			</u-cell-group>

		</view>


		<u-popup :show="show" @close="close" @open="open" mode="center" closeable round="4"
			:closeOnClickOverlay="false">
			<view class="popbox">
				<view class="popbox_title">
					填写信息
				</view>
				<view class="popbox_content">
					<u--form labelPosition="left" :model="completionInfo" :rules="rules" ref="uForm" labelWidth="80">

						<!-- <u-form-item required label="处理过程" prop="process" labelPosition="left">
							<u--textarea style="margin-top: 12px;" v-model="completionInfo.process" autoHeight
								placeholder="请输入处理过程"></u--textarea>
						</u-form-item>
						<u-form-item required label="处理结果" prop="result" labelPosition="left">
							<u--textarea style="margin-top: 12px;" v-model="completionInfo.result" autoHeight
								placeholder="请输入处理结果"></u--textarea>
						</u-form-item>
						<u-form-item required label="解决时间" prop="taskSolveDate" labelPosition="left">
							<uni-datetime-picker type="date" :clear-icon="true"
								@change="$refs.uForm.validateField('taskSolveDate')"
								v-model="completionInfo.taskSolveDate" />
						</u-form-item> -->
						<u-form-item required label="结果附件" prop="imgIds" labelPosition="left">
							<file-upload style="margin-top: 12px;" accept="file"
								@updataFile="updataImage"></file-upload>
						</u-form-item>
					</u--form>
				</view>
				<u-button type="primary" text="确定" @click="handleSubmit()"></u-button>
			</view>
		</u-popup>
		<bottom-button v-if="info.problemStatus =='3' && type == '1'" @click="handleConfirm"></bottom-button>
	</view>
</template>

<script>
	import {
		getDicts,
		getToDoTaskById,
		completeTask,
		getFileList,
		submitTaskProblem
	} from "@/common/api.js"
	import config from "@/common/config.js"
	import bottomButton from "@/components/bottomButton.vue";
	import typeTitle from "@/components/typeTitle.vue";
	import fileUpload from "@/components/fileUpload.vue";
	import dictsTag from "@/components/dictsTag.vue"
	import dicts from '@/mixins/dicts.js'
	export default {
		mixins: [dicts],
		components: {
			bottomButton,
			fileUpload,
			dictsTag,
			typeTitle
		},
		data() {
			return {
				formData: {}, // 存储表单数据，替代原硬编码的“11”
				formList: [{
						label: '工号',
						prop: 'productNo',
						type: 'select',
						status: 'normal',
						required: true,
						url: '/pages/product/index'
					},
					{
						label: '要求到厂日期',
						prop: 'arrivalFactoryDate',
						type: 'date',
						status: 'normal',
						required: true
					},
					{
						label: '要求完成日期',
						prop: 'requireDate',
						type: 'date',
						status: 'normal',
						required: true
					},
					{
						label: '备注',
						prop: 'remark',
						type: 'textarea',
						status: 'normal',
						required: true
					},
				],

				info: {
					problemList: []
				},
				taskId: '',
				baseFileUrl: config.baseFileUrl,
				imgList: [],
				type: '', // 页面类型
				disabled: false,
				imageList: [],
				fileList: [],
				dictList: {},
				show: false,
				rules: {
					process: [{
						required: true,
						message: '请输入处理过程',
						trigger: ['blur', 'change']
					}],
					result: [{
						required: true,
						message: '请输入处理结果',
						trigger: ['blur', 'change']
					}],
					taskSolveDate: [{
						required: true,
						message: '请选择解决时间',
						trigger: ['blur', 'change']
					}],
					imgIds: {
						type: 'array',
						required: true,
						min: 1,
						message: '请上传附件',
						trigger: ['change']
					},
				},
				completionInfo: {
					taskSolveDate: '', // 解决时间
					result: '', // 处理结果
					process: '', // 处理过程
					imgIds: "",
				},
				radiolist: [{
						value: '2',
						name: '是'
					},
					{
						value: '3',
						name: '否'
					}
				]
			};
		},
		onLoad(e) {
			this.taskId = e.taskId || ''
			this.type = e.type || ''
			this.disabled = e.type == 2 ? true : false
			this.getInfo()

			this.getDictsList('service_product_type')
			this.getDictsList('service_voltage_type')
			this.getDictsList('service_project_task_problem')

		},
		onReady() {
			if (this.type == 2)
				uni.setNavigationBarTitle({
					title: '详情'
				})
		},
		methods: {
			async getInfo() {
				let that = this
				let res = await getToDoTaskById({
					taskId: this.taskId
				})
				if (res.code == '00000') {
					this.info = res.data
					this.result = res.data.result

					this.getFile('task_problem_info_file')
					this.getFile('task_info_file')


					// if (this.info && this.info.problemStatus == '3' && this.info.problemList && this.info.problemList
					// 	.length) {
					// 	this.info.problemList.forEach(item => {
					// 		item.problemStatus = '2'
					// 	})

					// }



				}
			},
			async getDictsList(dictType) {
				let res = await getDicts({
					dictType: dictType
				})
				if (res) {
					this.dictList[dictType] = res.data
				}
			},
			updataImage(e) {
				this.completionInfo.imgIds = e;
				this.$refs.uForm.validateField('imgIds')
			},
			handleConfirm() {
				// 1. 检查是否所有问题都已确认（排除初始状态1）
				const allConfirmed = this.info.problemList.every(item => {
					return item.problemStatus === '2' || item.problemStatus === '3';
				});

				if (!allConfirmed) {
					const unconfirmedIndex = this.info.problemList.findIndex(item =>
						item.problemStatus === '1'
					);
					return this.$commonFn.msg(`请确认第${unconfirmedIndex + 1}个问题的完成情况`, 1500);
				}

				// 2. 检查所有选择"否"(3)的问题是否填写了备注
				const hasEmptyRemark = this.info.problemList.some(item => {
					return item.problemStatus === '3' && (!item.problemCause || item.problemCause.trim() === '');
				});

				if (hasEmptyRemark) {
					const emptyRemarkIndex = this.info.problemList.findIndex(item =>
						item.problemStatus === '3' && (!item.problemCause || item.problemCause.trim() === '')
					);
					return this.$commonFn.msg(`请为第${emptyRemarkIndex + 1}个问题（选择"否"）填写问题原因`, 1500);
				}

				// 3. 新增：检查每个问题的【解决时间】【处理过程】【处理结果】是否填写
				let valid = true;
				let errorMsg = '';

				this.info.problemList.forEach((item, index) => {
					if (!item.problemSolveDate) {
						valid = false;
						errorMsg = `第${index + 1}个问题：请选择解决时间`;
					} else if (!item.process || item.process.trim() === '') {
						valid = false;
						errorMsg = `第${index + 1}个问题：请填写处理过程`;
					} else if (!item.result || item.result.trim() === '') {
						valid = false;
						errorMsg = `第${index + 1}个问题：请填写处理结果`;
					}
				});

				if (!valid) {
					return this.$commonFn.msg(errorMsg, 1500);
				}

				// 4. 所有校验通过，显示弹窗（后续在弹窗中上传附件并提交）
				this.show = true;

				// 5. 弹窗显示时，清空之前的表单数据（避免缓存）
				this.completionInfo = {
					taskSolveDate: '',
					result: '',
					process: '',
					imgIds: "",
				};
			},
			handleItemComplete(item, index) {

				let that = this
				if (item.problemStatus == '1') return this.$commonFn.msg('请选择是否完成')
				if (item.problemStatus == '3' && !item['problemCause']) return this.$commonFn.msg('请填写未完成原因')
				if (!item.problemSolveDate) return this.$commonFn.msg('请选择解决时间')
				if (!item.process) return this.$commonFn.msg('请填写处理过程')
				if (!item.result) return this.$commonFn.msg('请填写处理结果')
				// console.log(item);
				let params = {
					problemStatus: item.problemStatus,
					problemStatus: item.problemStatus,
					problemSolveDate: item.problemSolveDate,
					process: item.process,
					result: item.result,
					problemCause: item.problemStatus === '2' ? '' : item.problemCause,
					problemId: item.problemId,
					taskId: this.info.taskId
				}
				uni.showModal({
					title: '提示',
					content: '确认是否完成问题' + index,
					success: function(res) {
						if (res.confirm) {
							uni.showLoading({
								title: '数据提交中',
								mask: true
							});
							submitTaskProblem(params).then(ord => {
								that.$commonFn.msg('提交成功')
								uni.hideLoading();
								that.getInfo()
							}).catch(err => {
								console.log(err, 'err')
								uni.hideLoading();
							})
						}
					}
				});
			},
			handleSubmit() {
				let that = this
				console.log(this.info, 'this.info')
				this.$refs.uForm.validate().then(res => {
					let params = JSON.parse(JSON.stringify(that.completionInfo))
					params['task_info_file'] = params['imgIds'].map(item => item.fileId).join(',')
					// params['bizType'] = 'task_info_file'
					params = {
						...this.info,
						...params,
					}
					uni.showLoading({
						title: '提交中',
						mask: true
					});

					completeTask(JSON.stringify(params), {
						header: {
							'Content-Type': 'application/json'
						}

					}).then(ord => {
						this.$commonFn.msg('提交成功')
						uni.hideLoading()
						this.show = false
						setTimeout(() => {
							that.$commonFn.Navback()
						}, 500);
					}).catch(err => {
						uni.hideLoading()
					})
				}).catch(errors => {
					uni.hideLoading()
					console.log(errors, 'errors')
				})
			},
			open() {

			},
			handleQuestion(item) {
				this.$set(item, 'checked', !item['checked'])
			},
			close() {
				this.show = false
			},
			async getFile(type) {
				let res = await getFileList({
					bizType: type,
					bizId: this.taskId
				})
				if (res.data) {
					if (type == 'task_problem_info_file') {
						this.fileList = res.data.map(item => {
							return {
								...item,
								url: config.baseFileUrl + item.fileId,
								name: item.fileName,
							}
						})
					} else {
						this.imageList = res.data.map(item => {
							return {
								...item,
								url: config.baseFileUrl + item.fileId,
								name: item.fileName,
							}
						})
					}
				}
			}
		},
	};
</script>

<style scoped lang="scss">
	.u-page {
		padding: 0;

		&__item {

			&__title {
				color: $u-tips-color;
				background-color: $u-bg-color;
				padding: 15px;
				font-size: 15px;

				&__slot-title {
					color: $u-primary;
					font-size: 14px;
				}
			}
		}
	}



	.question-title-item {
		color: #909193;
		padding: 12rpx 24rpx;
		font-size: 15px
	}

	.question-box {
		background-color: #fff;
		padding: 24rpx;
		border-radius: 12rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08); // 卡片阴影
		margin: 0 32rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;

		&-item {
			color: #606266;
			font-size: 30rpx;
			margin-bottom: 20rpx;
			display: flex;
			align-items: center;

			&>text:last-child {
				// color: #000;
				flex: 1;
			}

			&>text:first-child {
				flex-shrink: 0;
				width: 150rpx;
			}

			&:last-child {
				margin-bottom: 0;
			}
		}

		&-btn {
			padding-top: 24rpx;
			display: flex;
			justify-content: space-between;

		}

		&-left {
			flex: 1;
		}

		&-check {
			padding-left: 12rpx;
		}
	}

	.u-collapse-content {
		color: $u-tips-color;
		font-size: 15px;
		margin-bottom: 12rpx;
		color: #000;

	}

	.info-section {
		background-color: #fff;
		margin-bottom: 20rpx;
	}

	.question-section {
		// background-color: #fff;

		.question-title {
			line-height: 42px;
			text-align: center;
			// background-color: #3c9cff;
			// color: #fff;
			// font-size: 16px;
			// background-color: #f3f4f6;
			// padding-left: 14rpx;
		}

		&-btn {
			// padding-top: 24rpx;
		}
	}

	.result-box {
		margin-top: 20rpx;
		background-color: #fff;
	}

	// 修复文本对齐问题
	::v-deep {

		.uni-textarea-textarea,
		.uni-textarea-placeholder,
		.u-form-item__body__right__message,
		.u-textarea__field {
			// text-align: right !important;
		}

		.u-cell__body {
			justify-content: space-between;
		}

		.u-cell__body__content {
			flex-shrink: 1;
			padding-right: 10px;
			flex: 1;
			min-width: 150rpx;
			word-break: break-all;
		}

		.u-cell__value {
			word-break: break-all;

		}
	}

	.popbox {
		width: 698rpx;
		padding: 24rpx;
		padding-top: 32rpx;
		border-radius: 12rpx;

		&_title {
			text-align: center;
			padding-bottom: 24rpx;
		}

		&_content {
			padding-bottom: 24rpx;
		}
	}

	.color-blue {
		color: #2979ff;
	}

	.color-red {
		color: #fa3534;
	}

	.color-green {
		color: #19be6b;
	}
</style>